package com.example.figurehecheng.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.figurehecheng.common.context.BaseContext;
import com.example.figurehecheng.domain.dto.RestaurantDTO;
import com.example.figurehecheng.domain.entity.Image;
import com.example.figurehecheng.domain.entity.Restaurant;
import com.example.figurehecheng.domain.entity.Scenery;
import com.example.figurehecheng.domain.entity.Venues;
import com.example.figurehecheng.domain.vo.RestaurantVO;
import com.example.figurehecheng.domain.vo.SceneryVO;
import com.example.figurehecheng.mapper.RestaurantMapper;
import com.example.figurehecheng.service.IRestaurantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 餐厅表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-04
 */
@Service
@RequiredArgsConstructor
public class RestaurantServiceImpl extends ServiceImpl<RestaurantMapper, Restaurant> implements IRestaurantService {

    private final ImageServiceImpl imageServiceImpl;
    @Autowired
    private IRestaurantService restaurantService;

    /**
     * 创建餐厅
     *
     * @param dto
     * @return
     */
    @Override
    public Long createRestaurant(RestaurantDTO dto) {
        Restaurant restaurant = new Restaurant();
        if (dto == null) {
            throw new IllegalArgumentException("RestaurantDTO 不能为 null");
        }
        BeanUtils.copyProperties(dto, restaurant);
        // 设置默认状态为1（营业）
        restaurant.setStatus(1);
        restaurant.setCreateTime(LocalDateTime.now());
        restaurant.setUpdateTime(LocalDateTime.now());
        restaurant.setMid(BaseContext.getCurrentId().intValue());
        // 保存并返回ID
        save(restaurant);
        return restaurant.getId();
    }

    /**
     * 根据获取餐厅列表
     *
     * @param
     * @return
     */
    @Override
    public List<RestaurantVO> getRestaurantListByMid() {
        Integer mid = restaurantService.lambdaQuery().one().getMid();
        LambdaQueryWrapper<Restaurant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Restaurant::getMid, mid);
        List<Restaurant> restaurantList = list(queryWrapper);
//        System.out.println(restaurantList);
        //转换为VO对象
        return restaurantList.stream().map(restaurant -> {
            RestaurantVO vo = new RestaurantVO();
            BeanUtils.copyProperties(restaurant, vo);
            return vo;
        }).collect(Collectors.toList());
    }
    /**
     * 根据获取餐厅详情
     * @return
     */
    @Override
    public RestaurantVO getRestaurantByMid() {
        // 获取当前登录用户的商户ID
        int currentId = BaseContext.getCurrentId().intValue();
        System.out.println("currentId"+currentId);
        Integer mid = currentId;
        LambdaQueryWrapper<Restaurant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Restaurant::getMid, mid);
        // 查询数据
        Restaurant restaurant = getOne(queryWrapper);
        if (restaurant == null) {
            return null;
        }
        //查询关联的图片列表
        List<Image> images = imageServiceImpl.lambdaQuery()
                .eq(Image::getRelationId, mid)
                .list();
        //转化为VO对象
        RestaurantVO vo = new RestaurantVO();
        BeanUtils.copyProperties(restaurant, vo);
        if (images != null && !images.isEmpty()) {
            //将图片列表转换为图片URL列表
            List<String> imageUrls = images.stream()
                    .map(Image::getUrl)
                    .collect(Collectors.toList());
            vo.setImages(imageUrls);
            //设置图片列表
            vo.setImages(imageUrls);
        }
        return vo;
    }
    /**
     * 更新餐厅信息
     * @param dto
     * @return
     */
    @Override
    public boolean updateRestaurant(RestaurantDTO dto) {
        // 获取当前商家ID
        Integer currentId = BaseContext.getCurrentId().intValue();
        Integer  mid = currentId;
        LambdaQueryWrapper<Restaurant> qyueryWrapper = new LambdaQueryWrapper<>();
        qyueryWrapper.eq(Restaurant::getMid, mid);
        Restaurant oldRestaurant = getOne(qyueryWrapper);
        if (oldRestaurant == null) {
            throw new RuntimeException("餐厅不存在或无权修改");
        }
        //复制属性并更新
        Restaurant restaurant = new Restaurant();
        BeanUtils.copyProperties(dto, restaurant);
        restaurant.setMid(currentId);
        restaurant.setUpdateTime(LocalDateTime.now());
        restaurant.setStatus(oldRestaurant.getStatus());

        return updateById(restaurant);

    }

    @Override
    public List<RestaurantVO> queryRestaurantList() {
        LambdaQueryWrapper<Restaurant> qyueryWrapper = new LambdaQueryWrapper<>();

        // 只查询状态为1的餐厅
        qyueryWrapper.eq(Restaurant::getStatus, 1);
        // 默认按创建时间降序
        qyueryWrapper.orderByDesc(Restaurant::getCreateTime);

        // 查询数据
        List<Restaurant> restaurants = list(qyueryWrapper);
        List<RestaurantVO> result = new ArrayList<>();

        //转化为vo对象
        for (Restaurant restaurant : restaurants) {
            RestaurantVO vo = new RestaurantVO();
            BeanUtils.copyProperties(restaurant, vo);

            // 查询餐厅图片
            List<Image> images = imageServiceImpl.lambdaQuery()
                    .eq(Image::getRelationId, restaurant.getMid())
                    .list();

            if (images != null && !images.isEmpty()) {
                // 只取第一张图片作为封面
                vo.setCoverImage(images.get(0).getUrl());
            }

            result.add(vo);
        }
        return result;
    }

    /**
     * 根据餐厅名称搜索餐厅
     * @return
     */
    @Override
    public List<RestaurantVO> searchRestaurantByName(String name) {
        LambdaQueryWrapper<Restaurant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Restaurant::getName,  "%" + name + "%");
        List<Restaurant> restaurantslist = list(queryWrapper);
        return restaurantslist.stream().map(restaurants->{
            RestaurantVO vo = new RestaurantVO();
            BeanUtils.copyProperties(restaurants, vo);
            // 查询关联图片
            List<Image> images = imageServiceImpl.lambdaQuery()
                    .eq(Image::getRelationId, restaurants.getMid())
                    .list();
            if (images != null && !images.isEmpty()) {
                vo.setCoverImage(images.get(0).getUrl());
            }
            return vo;
        }).collect(Collectors.toList());
    }
}
